<?php

namespace app\api\controller\wm;


use app\common\controller\Api;
use app\common\model\Admin;
use app\common\model\wm;
use app\common\model\wm\Cart;
use app\common\model\wm\Category;
use app\common\model\wm\Goods as GoodsModel;




/**
 * 外卖商品
 * @ApiWeigh (96)
 */
class Goods extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['list', 'reclist', 'detail'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // protected $auth = ['test3'];

    /**
     * 商品分类
     * @Author xy
     * @ApiMethod (GET)
     * @ApiParams (name="admin_id", type="integer", required=true, sample="", description="店铺ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function category()
    {
        $rej = $this->validate(
            $this->request->param(),
            [
                'admin_id'  => 'require|number|egt:1',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $res = Category::where('admin_id', $this->request->param('admin_id'))
            ->order('weigh desc,id desc')
            ->select();

        $this->responseMsg(0, $res);
    }

    /**
     * 商品列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (GET)
     * @ApiParams (name="category_id", type="int", required=true, description="分类ID")
     * @ApiParams (name="admin_id", type="int", required=true, description="门店ID")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':'0','msg':'返回成功'})
     */
    public function list()
    {
        $param = $this->request->param();
        extract($param);
        $filed = 'id,price,title,title_de,thumb_image,images,stock,sale_num,intro,intro_de,admin_id';
        if ($category_id && $category_id > 0) {
            $res = GoodsModel::where('category_id', $category_id)
                ->where('sale_switch', 1)
                ->field($filed)
                ->order('weigh desc,sale_num desc,id desc')
                ->select();
        } else {
            $res = GoodsModel::where('admin_id', $admin_id)
                ->where('sale_switch', 1)
                ->field($filed)
                ->order('weigh desc,sale_num desc,id desc')
                ->select();
        }
        if ($this->auth->isLogin()) {
            foreach ($res as $v) {
                $v->cart_num = Cart::where('admin_id', $v->admin_id)->where('goods_id', $v->id)->where('user_id', $this->auth->id)->value('total');
            }
        }

        // $res = api_format_img($res,'thumb_image');
        // $res = mutrl_format_img($res,'images');

        $this->responseMsg(0, $res);
    }


    /**
     * 推荐商品
     * @ApiInternal
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, description="商品ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function reclist()
    {
        $rej = $this->validate(
            $this->request->param(),
            [
                'id'  => 'require|number',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $res = GoodsModel::get($this->request->param('id'));
        if (!$res) {
            $this->responseMsg(1007, '', '没有找到数据');
        }
        $res = GoodsModel::where('admin_id', $res->admin_id)
            ->where('auth_switch', 1)
            ->where('sale_switch', 1)
            ->where('stock', '>', 0)
            ->where('id', '<>', $this->request->param('id'))
            ->field('id,price,title,thumb_image,images,stock,sale_num,packing_price')
            ->limit(4)->select();
        $this->responseMsg(0, $res);
    }





    /**
     * 商品详情
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, description="商品id")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function detail()
    {

        $rej = $this->validate(
            $this->request->param(),
            [
                'id'  => 'require|number',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $res = GoodsModel::get($this->request->param('id'));
        if (!$res) {
            $this->responseMsg(1007, '', '没有找到数据');
        }
        $this->responseMsg(0, $res->toArray());
    }



    /**
     * 商品管理列表
     * @ApiInternal
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (GET)
     * @ApiParams (name="category_id", type="int", required=false, description="分类ID 不传为全部商品")
     * @ApiParams (name="title", type="str", required=false, description="搜索关键字")
     * @ApiParams (name="sale_switch", type="int", required=true, description="是否在售1=在售,0=下架")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':'0','msg':'返回成功'})
     */
    public function shoplist()
    {

        $user = $this->auth->getUser();
        $shop = Admin::where('user_id', $user->id)->find();
        if (!$shop) {
            $this->responseMsg(1006, '', '没有店铺');
        }
        if ($shop->status != '1') {
            $this->responseMsg(1006, '', '店铺没有通过审核，或已禁用');
        }
        $res = GoodsModel::where('admin_id', $shop->id);

        if ($this->request->param('category_id')) {
            $res = $res->where('category_id', $this->request->param('category_id'));
        }

        // if ($this->request->post('sale_switch') !== null) {
        $res = $res->where('sale_switch', $this->request->param('sale_switch'));
        // }

        if ($this->request->param('title')) {
            $res = $res->where('title', 'like', "%{$this->request->param('title')}%");
        }

        $res = $res->field('id,price,title,thumb_image,images,stock,sale_num,packing_price,weigh,auth_switch,sale_switch')
            ->order('weigh desc,sale_num desc,id desc')
            ->select();
        $this->responseMsg(0, $res);
    }
    /**
     * 添加商品
     * @ApiInternal
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="category_id", type="integer", required=true, description="分类ID")
     * @ApiParams (name="title", type="str", required=true, description="标题")
     * @ApiParams (name="price", type="float", required=true, description="价格")
     * @ApiParams (name="stock", type="integer", required=true, description="库存")
     * @ApiParams (name="intro", type="str", required=true, description="简介")
     * @ApiParams (name="thumb_image", type="str", required=true, description="封面图")
     * @ApiParams (name="images", type="str", required=false, description="轮播图-多图逗号分隔")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function add()
    {
        $user = $this->auth->getUser();
        $shop = Admin::where('user_id', $user->id)->find();
        if (!$shop) {
            $this->responseMsg(1006, '', '没有店铺');
        }
        if ($shop->status != '1') {
            $this->responseMsg(1006, '', '店铺没有通过审核，或已禁用');
        }
        $rej = $this->validate(
            $this->request->post(),
            [
                'title'  => 'require|max:255',
                'thumb_image'  => 'require|max:255',
                'category_id'  => 'require|number',
                'price'  => 'require|number|egt:0.01',
                'stock'  => 'require|number',
                'intro'  => 'require|max:255',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $data = $this->request->post();
        $data['admin_id'] = $shop->id;
        $data['school_id'] = $shop->school_id;
        $res = GoodsModel::create($data);
        if (!$res) {
            $this->responseMsg(1007, '', '添加失败');
        }
        //写入销量

        $this->responseMsg(0, $res->id);
    }

    /**
     * 编辑商品
     * @ApiInternal
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST&GET)
     * @ApiParams (name="id", type="integer", required=true, description="商品ID-下面参数仅post时需要")
     * @ApiParams (name="category_id", type="integer", required=true, description="分类ID")
     * @ApiParams (name="title", type="str", required=true, description="标题")
     * @ApiParams (name="price", type="float", required=true, description="价格")
     * @ApiParams (name="stock", type="integer", required=true, description="库存")
     * @ApiParams (name="intro", type="str", required=true, description="简介")
     * @ApiParams (name="thumb_image", type="str", required=true, description="封面图")
     * @ApiParams (name="images", type="str", required=false, description="轮播图-多图逗号分隔")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function edit()
    {
        $user = $this->auth->getUser();
        $shop = Admin::where('user_id', $user->id)->find();
        if (!$shop) {
            $this->responseMsg(1006, '', '没有店铺');
        }
        if ($shop->status != '1') {
            $this->responseMsg(1006, '', '店铺没有通过审核，或已禁用');
        }

        if ($this->request->isGet()) {
            $rej = $this->validate(
                $this->request->get(),
                [
                    'id' => 'require|number|egt:1'
                ]
            );
            if (true !== $rej) {
                $this->responseMsg(1005, [], $rej);
            }

            $res = GoodsModel::get($this->request->get('id'));
            if (!$res) {
                $this->responseMsg(1006, '', '没有找到该商品');
            }
            $this->responseMsg(0, $res);
        } else {
            $rej = $this->validate(
                $this->request->post(),
                [
                    'id' => 'require|number|min:1',
                    'title'  => 'require|max:255',
                    'thumb_image'  => 'require|max:255',
                    'category_id'  => 'require|number',
                    'price'  => 'require|number|egt:0.01',
                    'stock'  => 'require|number',
                    'intro'  => 'require|max:255',
                ]
            );
            if (true !== $rej) {
                $this->responseMsg(1005, [], $rej);
            }
            $res = GoodsModel::get($this->request->post('id'));
            if (!$res) {
                $this->responseMsg(1006, '', '没有找到该商品');
            }
            $data = $this->request->post();
            // $data['admin_id'] = $shop->id;
            foreach ($data as $k => $v) {
                if (in_array($k, ['title', 'thumb_image', 'category_id', 'price', 'stock', 'intro', 'packing_price'])) {
                    $res->$k = $v;
                }
            }
            $res->save();
            // $res->update($data, ['id' => $res->id], ['title', 'thumb_image', 'category_id', 'price', 'stock', 'intro', 'packing_price']);
            $this->responseMsg(0, $res);
        }
    }


    /**
     * 批量上下架
     * @ApiInternal
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="ids", type="str", required=true, description="商品ids-逗号分隔")
     * @ApiParams (name="sale_switch", type="int", required=true, description="1=上架,0=下架")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function changeSale()
    {
        $user = $this->auth->getUser();
        $shop = Admin::where('user_id', $user->id)->find();
        if (!$shop) {
            $this->responseMsg(1006, '', '没有店铺');
        }
        if ($shop->status != '1') {
            $this->responseMsg(1006, '', '店铺没有通过审核，或已禁用');
        }

        $rej = $this->validate(
            $this->request->post(),
            [
                'ids' => 'require|min:1',
                'sale_switch'  => 'require|in:0,1',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $goods = new GoodsModel;

        $goods->where('id', 'in', explode(',', $this->request->post('ids')))
            ->where('admin_id', $shop->id)
            ->update(['sale_switch' => $this->request->post('sale_switch')]);
        $this->responseMsg(0);
    }

    /**
     * 批量删除
     * @ApiInternal
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="ids", type="str", required=true, description="商品ids-逗号分隔")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function del()
    {
        $user = $this->auth->getUser();
        $shop = Admin::where('user_id', $user->id)->find();
        if (!$shop) {
            $this->responseMsg(1006, '', '没有店铺');
        }
        if ($shop->status != '1') {
            $this->responseMsg(1006, '', '店铺没有通过审核，或已禁用');
        }

        $rej = $this->validate(
            $this->request->post(),
            [
                'ids' => 'require|min:1',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        GoodsModel::where('id', 'in', explode(',', $this->request->post('ids')))
            ->where('admin_id', $shop->id)
            ->delete();
        $this->responseMsg(0);
    }

    /**
     * 更新排序
     * @ApiInternal
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="data", type="json", required=true, description="[{'id':1,'weigh':9},...]")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function changeWeigh()
    {
        $user = $this->auth->getUser();
        $shop = Admin::where('user_id', $user->id)->find();
        if (!$shop) {
            $this->responseMsg(1006, '', '没有店铺');
        }
        if ($shop->status != '1') {
            $this->responseMsg(1006, '', '店铺没有通过审核，或已禁用');
        }
        $data = $this->request->put();
        $rej = $this->validate(
            $data,
            [
                'data' => 'require',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $res = new GoodsModel;
        $list = $data['data'];
        $res->saveAll($list);
        $this->responseMsg(0);

        // $res->where('id', 'in', explode(',', $this->request->post('ids')))
        //     ->where('admin_id', $shop->id)
        //     ->update(['sale_switch']);
    }
}
